package com.hexinfo.dmpro.sparing.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import com.hexinfo.dmpro.common.utils.ConnExecuteUtil;
import com.hexinfo.dmpro.sparing.model.HdfsHeatBackup;
import com.hexinfo.dmpro.sparing.service.ThreadPoolService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ThreadPoolServiceImpl implements ThreadPoolService {

    @Value("${hdfs.heatBackup}")
    private String heatBackup;
    @Value("${heatBackup.logPath}")
    private String logPath;

    @Override
    @Async("threadPoolTaskExecutor")
    public void execShellCodes(HdfsHeatBackup hdfsHeatBackup,String strPath) {
        String shell = heatBackup + " " + hdfsHeatBackup.getSourceAddress() + " " + hdfsHeatBackup.getTargetAddress();
        int i = ConnExecuteUtil.execShellCode(shell);
        appendLog(strPath,"执行shell："+shell+"，执行结果："+i);
        if (i != 0){
//            appendLog(strPath,"按源执行错误shell："+shell);
            appendLogs(hdfsHeatBackup.getSourceData()+"/"+hdfsHeatBackup.getSourceData(),
                    "============按源执行错误shell："+shell+"  执行结果："+i);
        }
    }

    private void appendLog(String strPath,String str) {
        FileWriter writer = new FileWriter(strPath);
        writer.append("["+ DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss")+"]"
                +str+"\n");
    }

    public void appendLogs(String name,String str) {
        String strPath = logPath.replace("{date}", DateUtil.format(DateUtil.date(), "yyyyMMdd"))
                + name + ".txt";
        FileWriter writer = new FileWriter(strPath);
        writer.append("[" + DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss") + "]"
                + str + "\n");
    }

}
